package com.example.divesb.support;

import com.example.divesb.http.converter.json.PropertiesHttpMessageConverter;
import org.springframework.core.MethodParameter;
import org.springframework.http.HttpOutputMessage;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServletServerHttpResponse;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.context.request.ServletWebRequest;
import org.springframework.web.method.support.HandlerMethodReturnValueHandler;
import org.springframework.web.method.support.ModelAndViewContainer;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Properties;

public class PropertiesHandlerMethodReturnValueHandler implements HandlerMethodReturnValueHandler {
    @Override
    public boolean supportsReturnType(MethodParameter returnType) {
        return Properties.class.equals(returnType.getMethod().getReturnType());
    }

    @Override
    public void handleReturnValue(Object returnValue, MethodParameter returnType, ModelAndViewContainer mavContainer, NativeWebRequest webRequest) throws Exception {
        Properties properties = (Properties) returnValue;
        PropertiesHttpMessageConverter propertiesHttpMessageConverter =new PropertiesHttpMessageConverter();
        ServletWebRequest servletWebRequest = (ServletWebRequest) webRequest;

        HttpServletRequest request = (HttpServletRequest) servletWebRequest.getNativeRequest();
        HttpServletResponse response = (HttpServletResponse) servletWebRequest.getNativeResponse();

        HttpOutputMessage message =  new ServletServerHttpResponse(response);

        String ContentType =   request.getHeader("Content-Type");
        MediaType mediaType = MediaType.parseMediaType(ContentType);

        propertiesHttpMessageConverter.write(properties,mediaType,message);

        mavContainer.setRequestHandled(true);
    }
}
